import classnames from 'classnames'
import {useHistory} from 'react-router-dom'
import {NavBar, SearchBar} from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import {useState} from "react";
import {useDispatch, useSelector} from 'react-redux'
import {clearSuggestion, getSuggestion} from "@/store/actions/search";
// 函数的防抖功能
import {useDebounceFn, useLocalStorageState} from "ahooks";
import {SEARCH_KEY} from "@/store/constants";

const SearchPage = () => {
  const [searchText, setSearchText] = useState('');
  // 删除单条数据的功能
  // 不仅能够修改本次存储数据，同时还提供了一个变量，实时获取了本地存储的数据
  //
  const [searchHistories, setSearchHistories] = useLocalStorageState(SEARCH_KEY, {
    defaultValue: [],
  });
  const {suggestion} = useSelector(state => state.search)

  const history = useHistory()
  const dispatch = useDispatch()
  const {run} = useDebounceFn(
    value => dispatch(getSuggestion(value)),
    {
      wait: 500
    }
  )
  const onSearchChange = value => {
    setSearchText(value);
    if (!value) {
      // 代码需要rentrun
      dispatch(clearSuggestion())
      return
    }
    run(value)
  }
  // 最新搜索的放到最前面
  const saveHistories = value => {
    const localHistories = JSON.parse(localStorage.getItem(SEARCH_KEY) || '[]') // 获取本地存储的搜索历史记录数据
    let tempHistories = []
    if (localHistories.length === 0) {
      //  没有本地存储的
      tempHistories = [value]
    } else {
      //  已经有本地存储数据了
      const exist = localHistories.includes(value)
      if (exist) {
        /**
         *  当前搜索的内容放到第一个
         *  先把存在的过滤掉
         *  再把最新地放到最前面
         */
        const leftHistories = localHistories.filter(item => item !== value)
        tempHistories = [
          value,
          ...leftHistories
        ]
      } else {
        tempHistories = [
          value,
          ...localHistories
        ]
      }
    }

    // 搜索的过程中可以把搜索记录保存起来
    localStorage.setItem(SEARCH_KEY, JSON.stringify(tempHistories))
  }

  const onSearch = value => () => {
    // 跳转结果页面的时候把当前需要搜索的数据携带到结果页面
    // 搜索建议清空
    dispatch(clearSuggestion())
    saveHistories(value)
    history.push(`/search/result?q=${value}`)

  }
  const highlightSuggestion = suggestion.map(item => {
    const lowerItem = item.toLocaleLowerCase()
    const lowerSearchText = searchText.toLocaleLowerCase()
    const index = lowerItem.indexOf(lowerSearchText)
    const searchTxtLength = searchText.length
    return {
      left: item.slice(0, index), // (0, index)
      search: item.slice(index, index + searchTxtLength), // (index, index+searchText.length)
      right: item.slice(index + searchTxtLength),// (index+searchText.length, 结束)
    }
  })

  const handleDeleteHistoryItem = (value) => () => {
    const localHistories = searchHistories.filter(item => item !== value)
    // localstoreageHook设置值的时候，不仅能够操作本地存储，同时还会修改state状态
    setSearchHistories(localHistories)
  }

  //
  const clearAllHistories = () => {
    // ahooks里面的
    setSearchHistories([])
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={<span className="search-text" onClick={onSearch(searchText)}>搜索</span>}
      >
        <SearchBar onChange={onSearchChange} value={searchText} placeholder="请输入关键字搜索"/>
      </NavBar>

      {searchHistories.length > 0 && (
        <div
          className="history"
          style={{
            display: suggestion.length > 0 ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clearAllHistories}>
              <Icon type="iconbtn_del"/>
              清除全部
            </span>
          </div>

          <div className="history-list">
            {
              searchHistories.map(item => (
                <span className="history-item" key={item}>
                  <span className="text-overflow">{item}</span>
                  <Icon type="iconbtn_essay_close" onClick={handleDeleteHistoryItem(item)}/>
                </span>
              ))
            }
          </div>
        </div>
      )}

      <div className={classnames('search-result', suggestion.length > 0 ? 'show' : '')}>
        {
          highlightSuggestion.map((item, index) => (
            <div className="result-item" key={index} onClick={onSearch(item.left + item.search + item.right)}>
              <Icon className="icon-search" type="iconbtn_search"/>
              <div className="result-value text-overflow">
                {item.left}
                <span>{item.search}</span>
                {item.right}
                {/*{item}*/}
              </div>
            </div>
          ))
        }
      </div>
    </div>
  )
}

export default SearchPage
